package com.text.demo

import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.text.demo.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val viewBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)
        onInitFaceAgreeView(viewBinding.tvLivingAgreement)
    }

    private fun onInitFaceAgreeView(tvLivingAgreement: TextView) {
        tvLivingAgreement.highlightColor = Color.TRANSPARENT
        val content =
            """我已阅读并同意 《活体影像采集及授权协议》"""
        val tSpannableStringBuilder = SpannableStringBuilder()
        tSpannableStringBuilder.append(content)

        val startIndex = content.indexOf("《")
        val endIndex = content.indexOf("》") + 1

        //点击1
        val serveClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                Toast.makeText(widget.context, "服务协议", Toast.LENGTH_SHORT).show()
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.isUnderlineText = false
            }
        }
        tSpannableStringBuilder.setSpan(
            serveClickableSpan,
            startIndex,
            endIndex,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        //颜色1
        tSpannableStringBuilder.setSpan(
            ForegroundColorSpan(Color.parseColor("#2252FF")),
            startIndex,
            endIndex,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        //配置给TextView
        tvLivingAgreement.movementMethod = LinkMovementMethod.getInstance()
        tvLivingAgreement.text = tSpannableStringBuilder
    }
}